
<!--
 * @Descripttion: 
 * @version: 
 * @Author: 高月飞
 * @Date: 2023-11-19 14:01:10
 * @LastEditors: 高月飞
 * @LastEditTime: 2023-11-25 15:44:52
-->
<template>
    <div class="customerAll">
        <div class="allHeadvue">
            <div>
                <!-- 搜索 -->
                <allheadVue :loadData="loadData" :page="page" :pageSize="pageSize" />
            </div>
            <div>
                <!-- 按钮 -->
                <allBtnVue @importCustomer="importCustomer" @exposeCustomer="exposeCustomer" />
            </div>
        </div>
        <div class="gap"></div>
        <div class="allTableVueStylus">
            <!-- 表格 -->
            <allTableVue :data="data" :total="total" :loadData="loadData" :page="page" :pageSize="pageSize"
                @onSelectData="onSelectData" :tableData="tableData"  />
            <div class="gap"></div>
        </div>
        <div>
            <input ref="fileInputRef" type="file" style="display:none" @change="handleFileChange" />
        </div>

    </div>
</template>

<script setup lang="ts">
import allBtnVue from "./ui/allBtn.vue";
import allheadVue from "./ui/allhead.vue";
import allTableVue from "./ui/allTable.vue";
import { userDialogVisible, useCustomerList } from './allHooks'
import { useRoute } from "vue-router";
import { reactive, ref } from "vue";
import { ElLoading, valueEquals } from "element-plus";
import { successMessage } from "@/utils/Tools/successMessage";
import { errorMessage } from "@/utils/Tools/errorMessage";
import { readFile, utils } from "xlsx";
import type { ICustomerData } from "@/types/customer";
import * as XLSX from 'xlsx';
import { writeFile } from 'xlsx';
import { importUsersApi } from '@/services/customer'


interface IProps {
    page: number
    pageSize: number
}
const props = withDefaults(defineProps<IProps>(), {
    page: 1,
    pageSize: 10
})
const route = useRoute()
const [dialogVisible, setDialogVisible] = userDialogVisible()
const [data, total, loadData] = useCustomerList(props.page, route.query as object, props.pageSize)
//导入数据
const fileInputRef = ref<HTMLInputElement | null>(null);
const tableData = ref<any>([]);
const importCustomer = (value: boolean) => {
    if (value) {
        if (fileInputRef.value) {
            fileInputRef.value.click();
        }
    }

}
//导入数据
const handleFileChange = (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (file) {
        readExcel(file);
    }
};
const readExcel = (file: File) => {
    const reader = new FileReader();

    reader.onload = async (e) => {
        const data = e.target?.result;
        if (data) {
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
            const jsonDataWithoutHeader = jsonData.slice(1);

            console.log(jsonDataWithoutHeader)
            jsonDataWithoutHeader.forEach(item => {

                tableData.value.push(item)
            })
            console.log(tableData)
            let ret = await importUsersApi(tableData)
            if (ret.code === 200) {
                successMessage('导入用户记录成功', () => {

                }, 3000)
            }
            else {
                errorMessage('导入用户记录失败，请重新选中导出', () => {

                }, 3000)
            }
        }
    };

    reader.readAsBinaryString(file);
};
//选中用户
const exportCustomerTable = reactive<any>([])
const onSelectData = (selectedData: ICustomerData.ICustomerList[]) => {
    selectedData.forEach(item => exportCustomerTable.push(item))
}
//导出数据
const exposeCustomer = (value: boolean) => {
    if (value) {
        const loading = ElLoading.service({
            lock: true,
            text: '数据正在玩命导出生成中...',
            background: 'rgba(0, 0, 0, 0.6)'
        })
        try {
            const customHeaders: any = {
                'id': 'id',
                "customername": "客户名称",
                "customersex": "性别",
                "customercontact": "联系人",
                "customerbirthday": "生日",
                "customerphone": "联系电话",
                "customerprofile": "客户简介",
                "customeremail": "联系邮箱",
                "customerarea": "所属地区",
                "customerposition": "公司职位",
                "creditcode": "信用代码",
                "customersource": "客户来源",
                "followupstatus": "跟进状态",
                "customerlevel": "客户等级",
                "followuptime": "跟进时间",
                "intentionalproduct": "意向产品",
                "founder": "创建者",
                "followupdepartment": "跟进部门",
                "remark": "备注"
            };

            const exportCustomerData = exportCustomerTable.map((item: typeof exportCustomerTable[0]) => {
                const modifiedItem: any = {};
                for (const key in item) {
                    if (key in customHeaders) {
                        modifiedItem[customHeaders[key]] = item[key];
                    }
                }
                return modifiedItem;
            });
            // 把json数据导入为excel中的sheet数据类型
            const sheet = utils.json_to_sheet(exportCustomerData)
            // const sheet = utils.json_to_sheet(exportUserData(this.tableData))
            // 创建工作簿
            const workerBook = utils.book_new()
            utils.book_append_sheet(workerBook, sheet, 'Customer records')
            // 将工作簿数据写入或下载到文件
            writeFile(workerBook, 'Customer records.xlsx')
            successMessage('导出用户记录成功', () => {
                loading.close()
            }, 3000)
        } catch (err) {
            errorMessage('导出用户记录失败，请重新选中导出', () => {
                loading.close()
            }, 3000)
        }
    }
}



</script>

<style lang="scss" scoped>
.customerAll {
    width: 100%;
    height: 100%;
    border-radius: 20px;



    .allHeadvue {
        margin-bottom: 5px;
        background-color: red;
        border-radius: 10px;

        div {
            height: 60px;
            background-color: #fff;
        }

    }

    .gap {
        height: 10px;
        background-color: #f2f2f2;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        border: 0;
    }

    .allTableVueStylus {
        width: 100%;
        margin-top: 5px;
        border-radius: 10px;
    }


}

.el-overlay {
    .el-overlay-dialog {
        .el-dialog {

            .el-dialog__header {
                width: 100%;
                margin: 0;
                padding: 0;
                height: 50px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                background-color: red;

                .my-header {
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    text-align: center;

                    span {
                        width: 90%;
                        text-align: center;
                    }

                    i {
                        margin-right: 10px;
                    }


                }
            }
        }
    }

}

.closestylus {
    cursor: pointer;
}
</style>